import { getLastPage } from '@/utils'
import { tabBar as TABBAR } from '@/pages.json'

// 页面跳转兼容跳转tabbar
// 窗口动画 https://uniapp.dcloud.net.cn/api/router.html#animation

type AnimationType = UniNamespace.NavigateToOptions['animationType']

type BackAnimationType =
  | 'auto'
  | 'none'
  | 'pop-out'
  | 'slide-out-right'
  | 'slide-out-left'
  | 'slide-out-top'
  | 'slide-out-bottom'
  | 'fade-out'
  | 'zoom-in'
  | 'zoom-fade-in'

// 检测链接是否是tababr页面
export function hasTabbar(path: string) {
  const url = path || getLastPage().route
  return !!TABBAR.list.find((item) => item.pagePath.includes(url))
}

export function to(_page: string, animationType: AnimationType = 'pop-in') {
  _page = _page.startsWith('pages') ? _page : 'pages/' + _page

  if (hasTabbar(_page)) {
    uni.switchTab({
      url: '/' + _page,
    })
    return
  } else {
    uni.navigateTo({
      url: '/' + _page,
      // #ifdef APP-PLUS
      animationType,
      animationDuration: 300,
      // #endif
      fail: (err) => {
        console.log(err, '跳转失败', _page)
      },
    })
    return
  }
}

export function toLogin(isClose = false) {
  let path = 'pages-sub/public/login'
  isClose ? toRedi(path) : to(path)
}

// 关闭当前页跳转
export function toRedi(_page: string) {
  _page = _page.startsWith('pages') ? _page : 'pages/' + _page
  if (hasTabbar(_page)) {
    uni.switchTab({
      url: '/' + _page,
    })
    return
  }
  uni.redirectTo({
    url: '/' + _page,
    fail: (err) => {
      console.log(err)
    },
  })
}

// 关闭所有页面跳转
export function toRela(_page: string) {
  _page = _page.startsWith('pages') ? _page : 'pages/' + _page
  uni.reLaunch({
    url: '/' + _page,
  })
}

// tabbar跳转
export function toTab(_page: string) {
  _page = _page.startsWith('pages') ? _page : 'pages/' + _page
  uni.switchTab({
    url: '/' + _page,
  })
}

// 页面返回
export function toBack(delta = 1, animationType: BackAnimationType = 'pop-out') {
  uni.navigateBack({
    delta,
    // #ifdef APP-PLUS
    animationType,
    //#endif
  })
}

export default {
  to,
  toBack,
  toLogin,
  toRedi,
  toRela,
  toTab,
}
